package com.code2roc.fastboot.framework.auth;

import com.alibaba.fastjson.JSON;
import com.code2roc.fastboot.framework.redis.RedisUtil;
import com.code2roc.fastboot.framework.security.SecurityConfig;
import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.ReflectUtil;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {
    @Autowired
    private SecurityConfig securityConfig;
    @Autowired
    private RedisUtil redisUtil;

    public <T extends TokenModel> String createToken(T tokenModel) {
        String token = CommonUtil.getNewGuid();
        long redisExpire = securityConfig.getTokenExpire();
        //保存至redis缓存(允许前端读取的内容)
        Map<String, Object> mapvalue = new HashMap<>();
        Class clazz = tokenModel.getClass();
        List<Field> fs = ReflectUtil.getFieldList(clazz);
        try {
            for (Field field : fs) {
                field.setAccessible(true);
                if (!field.getName().equals("extraMap")) {
                    mapvalue.put(field.getName(), ConvertOp.convert2String(field.get(tokenModel)));
                }
            }
            mapvalue.put("extraMap", JSON.toJSONString(tokenModel.getExtraMap()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisUtil.redisTemplateSetForList(token, mapvalue);
        redisUtil.setExpire(token, redisExpire, TimeUnit.MINUTES);
        return token;
    }

    public boolean checkTokenValid(String token) {
        boolean flag = false;
        if (redisUtil.isValid(token)) {
            flag = true;
        }
        return flag;
    }

    public void removeToken(String token) {
        redisUtil.redisTemplateRemove(token);
    }

    public void refreshToken(String token) {
        //设置过期时间
        long redisExpire = securityConfig.getTokenExpire();
        TokenModel tokenModel = getTokenModel(token);
        if (tokenModel.getAutoRefreshExpire()) {
            redisUtil.setExpire(token, redisExpire, TimeUnit.MINUTES);
        }
    }

    public String getTokenString() {
        String token = "";
        HttpServletRequest request = CommonUtil.getRequest();
        if (request != null) {
            token = request.getHeader("token");
            if (token == null || token.equals("null") || token.equals("")) {
                token = request.getParameter("token");// 手机端的上传图片控件无法设置header ，所以加上这句。  打开编辑页面，为了使用model绑定，需要在layer弹出时增加参数token
            }
        }
        return token;
    }

    public TokenModel getTokenModel() {
        return getTokenModel(getTokenString());
    }

    public TokenModel getTokenModel(String token) {
        TokenModel model = new TokenModel();
        if (!StringUtil.isEmpty(token) && checkTokenValid(token)) {
            Map<Object, Object> map = redisUtil.redisTemplateGetForList(token);
            Class clazz = TokenModel.class;
            List<Field> fs = ReflectUtil.getFieldList(clazz);
            try {
                for (Field field : fs) {
                    field.setAccessible(true);
                    if (!field.getName().equals("extraMap") && !field.getName().equals("threadMap")) {
                        if (field.getType() == Boolean.class) {
                            field.set(model, ConvertOp.convert2Boolean(map.get(field.getName())));
                        } else {
                            field.set(model, map.get(field.getName()));
                        }
                    } else {
                        HashMap<String, String> extraMap = JSON.parseObject(ConvertOp.convert2String(map.get(field.getName())), HashMap.class);
                        for (String key : extraMap.keySet()) {
                            model.addExtra(key, extraMap.get(key));
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return model;
    }

    public <T extends TokenModel> T getTokenModel(Class<T> clazz) {
        return getTokenModel(getTokenString(), clazz);
    }

    public <T extends TokenModel> T getTokenModel(String token, Class<T> clazz) {
        T model = null;
        try {
            model = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtil.isEmpty(token) && checkTokenValid(token)) {
            Map<Object, Object> map = redisUtil.redisTemplateGetForList(token);
            List<Field> fs = ReflectUtil.getFieldList(clazz);
            try {
                for (Field field : fs) {
                    field.setAccessible(true);
                    if (!field.getName().equals("extraMap") && !field.getName().equals("threadMap")) {
                        if (field.getType() == Boolean.class) {
                            field.set(model, ConvertOp.convert2Boolean(map.get(field.getName())));
                        } else {
                            field.set(model, map.get(field.getName()));
                        }
                    } else {
                        HashMap<String, String> extraMap = JSON.parseObject(ConvertOp.convert2String(map.get(field.getName())), HashMap.class);
                        for (String key : extraMap.keySet()) {
                            model.addExtra(key, extraMap.get(key));
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return model;
    }

    public <T extends TokenModel> void setTokenModel(String token, T tokenModel) {
        Map<String, Object> mapvalue = new HashMap<>();
        Class clazz = tokenModel.getClass();
        List<Field> fs = ReflectUtil.getFieldList(clazz);
        try {
            for (Field field : fs) {
                field.setAccessible(true);
                if (field.getName().equals("extraMap")) {
                    mapvalue.put("extraMap", JSON.toJSONString(tokenModel.getExtraMap()));
                } else if (field.getName().equals("threadMap")) {
                    mapvalue.put("threadMap", JSON.toJSONString(tokenModel.getThreadMap()));
                } else if (field.getType() == List.class) {
                    mapvalue.put(field.getName(), JSON.toJSONString(field.get(tokenModel)));
                } else {
                    mapvalue.put(field.getName(), ConvertOp.convert2String(field.get(tokenModel)));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisUtil.redisTemplateSetForList(token, mapvalue);
    }
}
